package service_book

import (
	"math"
	"tools-api/src/common/db/database"
	"tools-api/src/jcj/model"
	"xorm.io/xorm"
)

// TypesGetList 获取类别列表
func TypesGetList(uuid string, _type int, isSet bool) []model.BookTypesResult {
	list := make([]model.BookTypesResult, 0)
	if isSet {
		list = model.BookTypes{}.GetTypesByType2(uuid, _type)
	} else {
		list = model.BookTypes{}.GetTypesByType(uuid, _type)
		// 非设置 添加设置选项
		list = append(list, model.BookTypesResult{ // 可选 VIP功能 TODO
			Id:   -1,
			Key:  "shezhi",
			Name: "设置",
			Sort: math.MaxInt32,
		})
	}
	return list
}

// TypesAdd 添加类别
func TypesAdd(types model.BookTypes) int64 {
	return types.Create()
}

// TypesSort 排序
func TypesSort(uuid string, list [][]int64) error {
	return sort("book_types", uuid, list)
}

// TypesDelete 删除类别
func TypesDelete(uuid string, id int64) error {
	return database.Session(database.JCJEngine.NewSession(), func(session *xorm.Session) error {
		// 删除类别
		err := model.BookTypes{}.Delete(session, uuid, id)
		if err != nil {
			return err
		}
		// 删除该类别下的记账明细
		err = model.BookDetail{}.DeleteDetailByTypes(session, uuid, id)
		return err
	})
}

// TypesTransformDelete 转移数据 并 删除类别
func TypesTransformDelete(uuid string, fromId, toId int64) error {
	return database.Session(database.JCJEngine.NewSession(), func(session *xorm.Session) error {
		// 转移数据
		err := model.BookDetail{}.TransformDetailByTypes(session, uuid, fromId, toId)
		if err != nil {
			return err
		}
		// 删除收支账户
		err = model.BookTypes{}.Delete(session, uuid, fromId)
		return err
	})
}
